package com.fhnew.app.widget;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.inputmethod.InputMethodManager;

import com.fhnew.app.R;
import com.fhnew.app.util.HLog;

import static android.content.Context.INPUT_METHOD_SERVICE;

public class CustomEditText extends android.support.v7.widget.AppCompatEditText {

    private int numberCount = 4;

    public CustomEditText (Context context) {
        super(context);
        init();
    }

    public CustomEditText (Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomEditText (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        addTextChangedListener(textWatcher);
    }

    public void setNumberCount(int numberCount){
        this.numberCount = numberCount;
    }


    @Override
    protected void onDraw (Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setStrokeWidth(2);
        paint.setColor(getResources().getColor(R.color.moccasin));

        int itemWidth = getMeasuredWidth()/4;
        for (int i = 1; i < numberCount; i++) {
            canvas.drawLine(itemWidth*i,0,itemWidth*i,getMeasuredHeight(),paint);
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        private CharSequence s;
        @Override
        public void beforeTextChanged (CharSequence s, int start, int count, int after) {

        }
        @Override
        public void onTextChanged (CharSequence s, int start, int before, int count) {
            this.s = s;
            if(s.length()==numberCount){
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindowToken(), 0);
            }
        }

        @Override
        public void afterTextChanged (Editable s) {
            if(s.length() > numberCount){
                setText(s.subSequence(0,numberCount));
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindowToken(), 0);
            }
        }
    };




}
